<?php
namespace Crontab\Controller;

use think\Controller;


//计算店铺的佣金类
class StoreController extends Controller{

    protected $storeModel;
    protected $memberModel;
    protected $orderModel;
    protected $storeBillModel;
    protected $storeBillDetailModel;
    protected $goodsSpecModel;
    protected $orderGoodsModel;
    public function _initialize(){
        $this->orderGoodsModel = D("order_goods");
        $this->goodsSpecModel = D("goods_spec");
        $this->storeModel = D("store");
        $this->memberModel = D("member");
        $this->orderModel = D('order');
        $this->storeBillModel = D("store_bill");
        $this->storeBillDetailModel = D("store_bill_detail");
    }

    public function calculation(){
        //查询所有合适的店铺信息
        $where = array('store_type'=>"shops","store_id" =>array("neq",2));
        $storeList = $this->storeModel->where($where)->select();


        $last_month_time= strtotime(date("Y-m-d H:i:s", strtotime("-1 month")));
        //上上个月时间(time)
        $last_last_month_time = strtotime(date("Y-m-d H:i:s", strtotime("-2 month")));
        //上上个月21号
        $start_time = strtotime(date('Y',$last_last_month_time).'-'.date('m',$last_last_month_time).'-21');
        //上个月20号
        $end_time = strtotime(date('Y',$last_month_time).'-'.date('m',$last_month_time).'-20 23:59:59');

        $s_time = date('Y-m-d H:i:s',$start_time);
        $e_time = date('Y-m-d H:i:s',$end_time);
        //查询符合当前时间段的所有订单
        $orderWhere = array(
            'finished_time' => array("between","$start_time,$end_time"),
            'status'      => array('in','40,50')        //40订单已完成  50订单已退款
        );
        $orderList = $this->orderModel->where($orderWhere)->select();
        $message = '查询当前时间段统计的符合记录返佣的订单列表'.$s_time.' ~~'.$e_time;
        writeLog($message);
        //声明一个字符串 组装所有的
        if(!empty($orderList)){
            $user_ids = '';
            foreach($orderList as $k=>$v){
                $sign = '+';
                if($v['status'] == 50){
                    $sign = '-';
                }
                //首先查看购买用户是否为个人推广的下级  是：则不进行返佣到线下店铺。  否：进行返佣
                $buyerUserInfo = $this->memberModel->where(array("user_id"=>$v['buyer_id']))->find();
                if(($buyerUserInfo['first_class'] != 0 || $buyerUserInfo['second_class'] != 0) && $buyerUserInfo['third_class'] == 0) {
                    //统计一级店铺的返佣金
                    $storeInfo = $this->storeModel->where(array('store_id' => $buyerUserInfo['first_class'],'store_type'=>'shops'))->find();
                    if(!empty($storeInfo)){
                        $this->commission($v, $start_time, $end_time, $buyerUserInfo, $storeInfo, $sign);
                        $message = '查询当前用户：' . $buyerUserInfo["user_id"] . ' 可进行一级店铺返佣';
                        writeLog($message);
                    }
                    if ($buyerUserInfo['second_class'] != 0) {
                        $storeInfoTwo = $this->storeModel->where(array('store_id' => $buyerUserInfo['second_class'],'store_type'=>'shops'))->find();
                        if(!empty($storeInfoTwo)){
                            $this->commission($v, $start_time, $end_time, $buyerUserInfo, $storeInfoTwo, $sign);
                            $message = '查询当前用户：' . $buyerUserInfo['user_id'] . ' 可进行二级店铺返佣';
                            writeLog($message);
                        }

                    }
                }
            }
        }
    }

    //计算佣金方法
    protected function commission($orderInfo,$start_time,$end_time,$userInfo,$storeInfo,$sign='+'){
        //拼接查询当前时间段和当前店铺的账单是否存在
        $where['start_time'] = $start_time;
        $where['store_id'] = $storeInfo['store_id'];
        $storeBillInfo = $this->storeBillModel->where($where)->find();
        $msssage = '当前用户'.$userInfo['user_id'].' 给当前店铺：'.$storeInfo['store_id'].' 进行返佣';
        $msssage.= '查询是否有返佣记录！';
        writeLog($msssage);
        //查询订单商品表信息
        $orderGoods = $this->orderGoodsModel->where(array('order_id'=>$orderInfo['order_id']))->find();
        //查询商品规格信息
        $goodsSpecInfo = $this->goodsSpecModel->where(array('spec_id'=>$orderGoods['spec_id']))->find();
        $time = time();
        if(!empty($storeBillInfo)){
            $message = '已查到有返佣记录';
            writeLog($message);
            //加入到佣金详情表
            $this->commonFunction($orderInfo,$orderGoods,$goodsSpecInfo,$storeInfo,$sign,$time,$storeBillInfo['id'],$storeBillInfo);
        }else{
            $sn =  date('YmdHis', time() + 8 * 3600) . rand(1000, 9999);
            $billData = array(
                'store_id'   => $storeInfo['store_id'],
                'account_no' => $sn,
                'start_time' => $start_time,
                'end_time'   => $end_time,
                'status'     => 1,
                'commission_money' => 0.00
            );
            $addBill = $this->storeBillModel->add($billData);
            $message = '未查到有返佣记录：进行新增记录操作！,加入数据'.json_encode($billData);
            writeLog($message);
            $this->commonFunction($orderInfo,$orderGoods,$goodsSpecInfo,$storeInfo,$sign,$time,$addBill,$billData);
        }
    }

    public function commonFunction($orderInfo,$orderGoods,$goodsSpecInfo,$storeInfo,$sign,$time,$billID,$storeBillInfo){
        if(!$this->storeBillDetailModel->where(array("order_id"=>$orderInfo['order_id'],"store_id"=>$storeBillInfo['store_id']))->find()){
            $data = json_encode(array(
                'order_id'              => $orderInfo['order_id'],
                'order_sn'              => $orderInfo['order_sn'],
                'buyer_id'              => $orderInfo['buyer_id'],
                'goods_id'              => $orderGoods['goods_id'],
                'spec_id'               => $orderGoods['spec_id'],
                'goods_name'            => $orderGoods['goods_name'],
                'sku'                   => $goodsSpecInfo['sku'],
                'num'                   => $orderGoods['quantity'],
                'price'                 => $orderGoods['price'],
                'price_amount'          => $orderInfo['order_amount'],
                'commission_proportion' => $storeInfo['sub'],
                'commission'            => $orderInfo['commission_amount'],
                'stock_style'           => $goodsSpecInfo['spec_3'],
            ));
            $addDetailData = array(
                'sign'                  => $sign,
                'order_pay_time'        => $orderInfo['pay_time'],
                'order_finish_time'     => $time,
                'commission_finish_time'=> $time,
                'store_id'              => $storeInfo['store_id'],
                'store_name'            => $storeInfo['store_name'],
                'serial_number'         => $storeInfo['serial_number'],
                'data'                  => $data,
                'store_account_id'      => $billID,
                'order_id'              => $orderInfo['order_id'],
            );
            $message = '进行新增详细信息操作：操作数据：'.json_encode($addDetailData);
            writeLog($message);
//        //新增一条详情记录
            $addDetail = $this->storeBillDetailModel->add($addDetailData);
            if($sign == '+'){
                $saveData['commission_money'] = $storeBillInfo['commission_money'] + $orderInfo['commission_amount'];
            }else{
                $saveData['commission_money'] = $storeBillInfo['commission_money'] - $orderInfo['commission_amount'];
            }
            $saveData['order_money'] = $storeBillInfo['order_money'] + $orderInfo['order_amount'];
            $saveBill = $this->storeBillModel->where(array("id"=>$billID))->save($saveData);
        }
    }


}